#include "./work.h"
#include <thread>
#include "../utils/message_queue.h"
#include "../utils/log.h"

namespace rt {

class HandlerThread {

public:
    void start() {
        m_task = std::thread(&HandlerThread::run, this);
    }

    void exit() {
        m_mq.interrupt();
        m_task.join();
    }

    void post(HandlerPtr&& ptr) {
        m_mq.put(std::move(ptr));
    }

private:
    void run() {
        for (;;) {
            try {
                HandlerPtr f = m_mq.take();
                f->exec();
            } catch (...) {
                break;
            }
        }
        log_printf("handler thread exit");
    }

private:
    std::thread m_task;
    utils::MessageQueue<HandlerPtr> m_mq;
};

static std::unique_ptr<HandlerThread> defaultThread;

void init() {
    defaultThread = std::make_unique<HandlerThread>();
    defaultThread->start();
}

void exit() {
    defaultThread->exit();
}

void post_to_default(HandlerPtr&& ptr) {
    defaultThread->post(std::move(ptr));
}

}

